package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.Inbox_Transactions_Table;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.Inbox_Warranty_Transfer_Inner_Table;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.model.RedeemCodeObject;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import com.warrantyhotel.android.util.ToastUtil;

public class InboxTransactionDetail extends Activity implements AsyncQueryListener, Receiver {

	private TextView txtInboxTransaction;
	private TextView txtInboxInformationTitle;
	private TextView txtInboxResponceTitle;
	private NotifyingAsyncQueryHandler mHandler;
	private ListView list;
	private ListAdapter adapter;
	private String guid;
	private DetachableResultReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox_transaction_detail);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		txtInboxInformationTitle = (TextView) findViewById(R.id.inbox_information_title_transaction);
		txtInboxTransaction = (TextView) findViewById(R.id.inbox_description_information_transaction);
		txtInboxResponceTitle = (TextView) findViewById(R.id.inbox_responce_information_transaction);

		list = (ListView) findViewById(R.id.inner_warranty_list);
		guid = getIntent().getExtras().getString(Keys._guid);
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		retrieveInboxTransactionId(guid);
		retrieveInnerWarranty(guid);

	}

	private void retrieveInboxTransactionId(String guid) {
		String[] projectionNews = { Inbox_Transactions_Table._ID, Inbox_Transactions_Table.GUID, Inbox_Transactions_Table.TEASER,
				Inbox_Transactions_Table.TITLE };
		mHandler.startQuery(QueriesCodes.INBOX_TRANSACTION, Inbox_Transactions_Table.CONTENT_URI, projectionNews, Inbox_Transactions_Table.GUID + " = '" + guid
				+ "'", null, null);
	}

	private void retrieveInnerWarranty(String guid) {
		String[] projectionInner = { Inbox_Warranty_Transfer_Inner_Table._ID, Inbox_Warranty_Transfer_Inner_Table.WARRANTY_TRANSACTION_ID,
				Inbox_Warranty_Transfer_Inner_Table.WARRANTY_ID, Inbox_Warranty_Transfer_Inner_Table.ITEM_NAME, Inbox_Warranty_Transfer_Inner_Table.STORE_NAME };
		mHandler.startQuery(QueriesCodes.INBOX_INNER_WARRANTY, Inbox_Warranty_Transfer_Inner_Table.CONTENT_URI, projectionInner,
				Inbox_Warranty_Transfer_Inner_Table.WARRANTY_TRANSACTION_ID + " = '" + guid + "'", null, null);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.INBOX_TRANSACTION:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					String teaser = cursor.getString(cursor.getColumnIndex(Inbox_Transactions_Table.TEASER));
					txtInboxTransaction.setText(teaser);
					String title = cursor.getString(cursor.getColumnIndex(Inbox_Transactions_Table.TITLE));
					txtInboxInformationTitle.setText(title);
				}
			}
			break;
		case QueriesCodes.INBOX_INNER_WARRANTY:
			if (cursor != null) {
				startManagingCursor(cursor);
				adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.inbox_item_inner, cursor, new String[] {
						Inbox_Warranty_Transfer_Inner_Table.ITEM_NAME, Inbox_Warranty_Transfer_Inner_Table.STORE_NAME }, new int[] {
						R.id.inbox_inner_title_item, R.id.inbox_inner_description_item });
				list.setAdapter(adapter);

			}
			break;
		}

	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			break;
		case UpdateIntentService.STATUS_ERROR:
			break;
		case UpdateIntentService.STATUS_FINISHED:
			if (resultData.containsKey(Keys.actionIdentificator) && resultData.getInt(Keys.actionIdentificator) == QueriesCodes.INBOX_INNER_WARRANTY_CHECK) {
				RedeemCodeObject redeemCode = resultData.getParcelable(Keys._redeemCode);
				showDial(redeemCode.getMessage());

			} else if (resultData.containsKey(Keys.actionIdentificator)
					&& resultData.getInt(Keys.actionIdentificator) == QueriesCodes.INBOX_INNER_WARRANTY_COMSUME) {
				RedeemCodeObject redeemCode = resultData.getParcelable(Keys._redeemCode);
				ToastUtil.showText(getApplicationContext(), redeemCode.getMessage());
				if (redeemCode.isSuccess()) {
					getContentResolver().delete(Inbox_Transactions_Table.CONTENT_URI, Inbox_Transactions_Table.GUID + " = '" + guid + "'", null);
					finish();
				}

			} else if (resultData.containsKey(Keys.actionIdentificator)
					&& resultData.getInt(Keys.actionIdentificator) == QueriesCodes.INBOX_INNER_WARRANTY_DISCARD) {
				RedeemCodeObject redeemCode = resultData.getParcelable(Keys._redeemCode);
				ToastUtil.showText(getApplicationContext(), redeemCode.getMessage());
				txtInboxResponceTitle.setText(redeemCode.getMessage());

				if (redeemCode.isSuccess()) {
					getContentResolver().delete(Inbox_Transactions_Table.CONTENT_URI, Inbox_Transactions_Table.GUID + " = '" + guid + "'", null);
					finish();
				}

			}

			break;
		}

	}

	private void showDial(String message) {

		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setTitle(getString(R.string.warranty_transfer));
		builder1.setMessage(message);
		builder1.setPositiveButton(getString(R.string.ok), new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				Intent comsumeIntent = new Intent(Intent.ACTION_SYNC, null, InboxTransactionDetail.this, UpdateIntentService.class);
				comsumeIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
				comsumeIntent.putExtra(Keys._warrantyTransactionID, guid);
				comsumeIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.INBOX_INNER_WARRANTY_COMSUME);
				startService(comsumeIntent);

			}
		});
		builder1.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		builder1.create();
		builder1.show();

	}

	private void showDialDiscard() {

		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setTitle(getString(R.string.warranty_transfer));
		builder1.setMessage(getString(R.string.discard_is_unreversable));
		builder1.setPositiveButton(getString(R.string.ok), new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				Intent discardIntent = new Intent(Intent.ACTION_SYNC, null, InboxTransactionDetail.this, UpdateIntentService.class);
				discardIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
				discardIntent.putExtra(Keys._warrantyTransactionID, guid);
				discardIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.INBOX_INNER_WARRANTY_DISCARD);
				startService(discardIntent);

			}
		});
		builder1.setNegativeButton(getString(R.string.cancel), new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		builder1.create();
		builder1.show();

	}

	public void onAccept(View view) {
		Intent checkIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		checkIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		checkIntent.putExtra(Keys._warrantyTransactionID, guid);
		checkIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.INBOX_INNER_WARRANTY_CHECK);
		startService(checkIntent);
	}

	public void onDiscard(View view) {
		showDialDiscard();
	}

}